import { TOKEN_STORAGE_KEY } from '@/constants/config';
import { useAppStore } from '@/store/app';
import storage from '@/utils/storage';
import Keycloak from 'keycloak-js';
import conf from '../config';

export const initOptions = {
  url: conf.kcDomain + '/auth',
  realm: 'numa-realm',
  clientId: 'decision-engine'
};

export const keycloakRef = ref<Keycloak | null>();

export const initKeycloak = async (appMount?: TAnyFunction) => {
  const { getMcisaas } = useAppStore();
  keycloakRef.value = Keycloak(initOptions);
  // const token = storage.get(TOKEN_STORAGE_KEY);
  // 白名单处理, 白名单路由 & 不需要重新加载kc
 /**  if (token) {
    // 获取登录信息
    await getMcisaas();
    // 挂载节点
    appMount?.();
    return Promise.resolve(keycloakRef.value);
  } */
  try {
    await keycloakRef.value.init({
      redirectUri: location.href,
      responseMode: 'query',
      onLoad: 'login-required'
    });
    if (keycloakRef.value.token) storage.set(TOKEN_STORAGE_KEY, keycloakRef.value.token, { time: 10, unit: 'hour' });
    // 获取登录信息
    await getMcisaas();
    // 挂载节点
    appMount?.();
  } catch (err) {
    if (err === undefined) {
      console.error('kc登录失败');
    }
  } finally {
    return Promise.resolve(keycloakRef.value);
  }
};

export function useKc() {
  const isNeedLogout = ref(false);
  const kcUserInfo = computed(() => {
    const token = keycloakRef.value?.token || storage.get(TOKEN_STORAGE_KEY);
    if (token) {
      return JSON.parse(decodeURIComponent(window.atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))));
    }
    return {};
  });

  const logout = () => {
    try {
      // keycloakRef.value?.logout();
      const urlName = import.meta.env.TYPE === 'dev' ? '' : '/decision-engine/';
      keycloakRef.value?.logout?.({ redirectUri: window.location.origin + urlName });
    } catch (error) {
      location.reload();
    }
  };

  return {
    logout,
    kcUserInfo,
    isNeedLogout
  };
}
